<?php

namespace App\Models\Product;

use App\Helpers\Code;
use App\Models\BaseModel;
use App\Models\Basic\DictionaryMember;
use App\Models\Customer\Customer;
use App\Models\Customer\CustomerDepartment;
use App\Models\Customer\Doctor;
use App\Models\Account\User;
use Illuminate\Support\Facades\Auth;

class Project extends BaseModel
{
    protected $table = 'projects';
    protected $fillable = [
        'title', 'code', 'description', 'state', 'customer', 'department', 'doctor', 'organization',
        'type', 'leader', 'salesman', 'money', 'created_by', 'updated_by', 'data_scope'
    ];
    public $sorters = [];
    public $params = ['code', 'title', 'doctor', 'type', 'description', 'leader'];

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'updated_by');
    }

    public function customer()
    {
        return $this->belongsTo('App\Models\Customer\Customer', 'customer');
    }

    public function department()
    {
        return $this->belongsTo('App\Models\Customer\CustomerDepartment', 'department');
    }

    public function doctor()
    {
        return $this->belongsTo('App\Models\Customer\Doctor', 'doctor');
    }

    public function organization()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'organization', 'code');
    }

    public function type()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'type', 'code');
    }

    public function salesman()
    {
        return $this->belongsTo('App\Models\Account\User', 'salesman');
    }

    public function leader()
    {
        return $this->belongsTo('App\Models\Account\User', 'leader');
    }

    /*添加项目*/
    public function addProject($data)
    {
        if (isset($data['customer']) && !empty($data['customer'])) {
            $customer = Customer::find($data['customer']);
            if (!$customer) {
                return null;
            }
        }

        if (isset($data['department']) && !empty($data['department'])) {
            $department = CustomerDepartment::find($data['department']);
            if (!$department) {
                return null;
            }
        }

        if (isset($data['doctor']) && !empty($data['doctor'])) {
            $doctor = Doctor::find($data['doctor']);
            if (!$doctor) {
                return null;
            }
        }

        if (isset($data['organization']) && !empty($data['organization'])) {
            $organization = DictionaryMember::find($data['organization']);
            if (!$organization) {
                return Code::INSIDE_ERROR;
            }
            $data['organization'] = $organization->code;
        }

        if (isset($data['type']) && !empty($data['type'])) {
            $type = DictionaryMember::find($data['type']);
            if (!$type) {
                return Code::INSIDE_ERROR;
            }
            $data['type'] = $type->code;
        }

        if (isset($data['leader']) && !empty($data['leader'])) {
            $leader = User::find($data['leader']);
            if (!$leader) {
                return Code::INSIDE_ERROR_1;
            }
        }

        if (isset($data['salesman']) && !empty($data['salesman'])) {
            $salesman = User::find($data['salesman']);
            if (!$salesman) {
                return Code::INSIDE_ERROR_1;
            }
        }

        $userId = Auth::id();
        $data['state'] = 1;
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    /*编辑项目*/
    public function editProject($data, $id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }

        if (isset($data['customer']) && !empty($data['customer'])) {
            $customer = Customer::find($data['customer']);
            if (!$customer) {
                Code::INSIDE_ERROR;
            }
        }

        if (isset($data['department']) && !empty($data['department'])) {
            $department = CustomerDepartment::find($data['department']);
            if (!$department) {
                Code::INSIDE_ERROR;
            }
        }

        if (isset($data['doctor']) && !empty($data['doctor'])) {
            $doctor = Doctor::find($data['doctor']);
            if (!$doctor) {
                Code::INSIDE_ERROR;
            }
        }

        if (isset($data['organization']) && !empty($data['organization'])) {
            $organization = DictionaryMember::find($data['organization']);
            if (!$organization) {
                return Code::INSIDE_ERROR_1;
            }
        }

        if (isset($data['type']) && !empty($data['type'])) {
            $type = DictionaryMember::find($data['type']);
            if (!$type) {
                return Code::INSIDE_ERROR_1;
            }
        }

        if (isset($data['leader']) && !empty($data['leader'])) {
            $leader = User::find($data['leader']);
            if (!$leader) {
                return Code::INSIDE_ERROR_2;
            }
        }

        if (isset($data['salesman']) && !empty($data['salesman'])) {
            $salesman = User::find($data['salesman']);
            if (!$salesman) {
                return Code::INSIDE_ERROR_2;
            }
        }

        $data['updated_by'] = Auth::id();
        return $model->updateOrCreate($data);
    }

    /*获取指定项目*/
    public function getProject($id)
    {
        $model = $this->with(['createdBy:id,username', 'updatedBy:id,username', 'salesman:id,username', 'leader:id,username', 'customer:id,title', 'department:id,title', 'doctor:id,title', 'organization:code,title', 'type:code,title'])
            ->where('id', $id)
            ->select(['id', 'title', 'code', 'state', 'description', 'state', 'customer', 'department', 'doctor', 'organization', 'type',
                'leader', 'salesman', 'money', 'created_by', 'updated_by', 'created_at', 'updated_at'])
            ->first();

        if(!$model){
            return null;
        }

        return $model;
    }

    /*获取项目列表*/
    public function getProjectList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->with(['createdBy:id,username', 'updatedBy:id,username', 'salesman:id,username', 'leader:id,username', 'customer:id,title', 'department:id,title', 'doctor:id,title', 'organization:code,title', 'type:code,title'])
            ->select(['id', 'title', 'code', 'state', 'description', 'state', 'customer', 'department', 'doctor', 'organization', 'type',
                'leader', 'salesman', 'money', 'created_by', 'updated_by', 'created_at', 'updated_at']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                case 'description':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
                case 'leader':
                    $model->whereHas('leader', function ($query) use ($key, $value) {
                        $query->where('username', 'like', '%' . $value . '%');
                    });
                    break;
                case 'type':
                    $model->whereHas('type', function ($query) use ($key, $value) {
                        $query->where('title', 'like', '%' . $value . '%');
                    });
                    break;
                case 'doctor':
                    $model->whereHas('doctor', function ($query) use ($key, $value) {
                        $query->where('title', 'like', '%' . $value . '%');
                    });
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }
}
